<template>
  <el-dialog
    :visible.sync="dialogFormVisible"
    :close-on-click-modal="false"
    append-to-body
    class="medium-common-dialog-size filter-dialog"
    @close="closeDialog">
    <div style="display:flex;margin-bottom:10px;align-items:center;">
      <Title title="筛选项配置" />
      <el-button size="small" type="primary" @click="addItem">新增</el-button>
    </div>
    <div v-if="filterList.length" :style="{maxHeight: tableHeight + 'px'}" class="scroll main">
      <div v-for="(item, index) in filterList" :key="index" class="filter-item">
        <el-select v-model="item.top" class="filter-120" popper-class="global-select-down" size="small" @change="changeTop(item)">
          <!-- 系统数据下拉 -->
          <el-option
            v-for="opt in systemConditionOptions.condition"
            :key="opt.id"
            :label="opt.name"
            :value="opt.id" />
        </el-select>
        <!-- 字段选择 -->
        <el-select v-if="systemConditionOptions" v-model="item.field" class="filter-120" popper-class="global-select-down" size="small" name="filterField" @change="changeField(item)">
          <el-option
            v-for="opt in item.systemSecondcondition || []"
            :key="opt.name"
            :label="opt.name"
            :value="opt.name" />
        </el-select>
        <!-- 根据不同的字段类型选择内容 -->
        <selectSystemField
          :item="item"
          :system-condition-options="systemConditionOptions"
          :time-range-type-options="timeRangeTypeOptions"
          :link-children="true"
          class="selectSystemField"
          mode="default"
          @timeRangeTypeChange="timeRangeTypeChange"
          @timeChange="timeChange" />
        <div class="delete-btn" @click="deleteItem(index)">
          删除
        </div>
      </div>
    </div>
    <div v-else class="empty">暂无筛选项</div>
    <div class="btn-container">
      <el-button type="primary" size="small" @click="toSubmit()">确定</el-button>
      <el-button type="info" size="small" class="cancel-btn-style" @click="closeDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import Title from '@/components/Title';
import { getOptionsData, setGlobalFilter } from '@/api/reportManage';
// tool
import toolMixin from '@/components/ReportManage/dataFilter/mixins/toolMethods';
// components
import selectSystemField from '@/components/ReportManage/dataFilter/selectSystemField';
export default {
  components: { Title, selectSystemField },
  mixins: [toolMixin],
  props: {
    tabId: {
      type: String | Number,
      default: ''
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      filterList: [],
      systemConditionOptions: {},
      timeRangeTypeOptions: [
        { id: '', name: '等于' },
        { id: 'day', name: '今日' },
        { id: 'yesterday', name: '昨日' },
        { id: 'week', name: '本周' },
        { id: 'lastweek', name: '上周' },
        { id: 'month', name: '本月' },
        { id: 'lastmonth', name: '上月' },
        { id: 'year', name: '本年' },
        { id: 'lastyear', name: '去年' },
        { id: '30days', name: '近30日' }
      ]
    };
  },
  methods: {
    /**
     * 触发事件
     */
    changeTop(item) {
      this.setYystemSecondcondition(item);
      this.changeSelectType(item, true);
    },
    // 时间类型改变：day:今日 week:本周 month:本月 year:本年，yesterday:昨日 lastweek:上周 lastmonth:上月 lastyear:去年
    timeRangeTypeChange(item) {
      if (item.timeRangeType !== '') {
        item.timeRange = [];
        item.begin = '';
        item.end = '';
      }
    },
    // 系统字段改变
    changeField(item) {
      this.changeSelectType(item);
      const curentField = item.systemSecondcondition.find(i => {
        return i.name === item.field;
      });
      if (curentField) {
        item.optionsType = curentField.optionsType;
      }
    },
    timeChange(time, item) {
      // 时间区间改变
    },
    // 报表的type改变 或者 系统的field改变
    changeSelectType(item, resetField = false) {
      if (resetField) this.$set(item, 'field', '');
      this.$set(item, 'optionsType', '');
      const isTime = this.isTimeField(item);
      if (isTime) {
        item.defaultMath = '';
      } else {
        item.defaultMath = '=';
      }
      this.$set(item, 'defaultValue', '');
      this.$set(item, 'defaultTimeRange', []);
      this.$set(item, 'defaultNumberRange', []);
    },
    // 获取系统筛选相关下拉选项
    async getOptionsData() {
      try {
        const res = await getOptionsData();
        if (res.data) {
          this.systemConditionOptions = res.data.conditionOptions;
          this.filterList.forEach(i => {
            this.setYystemSecondcondition(i);
          });
        }
      } catch (error) {
        console.error(error);
      }
    },
    setYystemSecondcondition(item) {
      // 系统
      if (item.top !== 0) {
        const f = this.systemConditionOptions.condition.filter(i => i.id === item.top);
        if (f && f.length) this.$set(item, 'systemSecondcondition', f ? f[0].field : []);
      }
    },
    deleteItem(index) {
      this.filterList.splice(index, 1);
    },
    addItem() {
      const initData = {
        top: null,
        field: '',
        optionsType: '',
        defaultMath: '=', // 操作，=,>,<,>=,<= 和 包含，不包含，首字
        defaultValue: '',
        defaultTimeRange: [],
        defaultNumberRange: []
      };
      this.filterList.push(initData);
    },
    toSubmit() {
      let filterList = JSON.parse(JSON.stringify(this.filterList));
      filterList = filterList.filter(i => i.field);
      this.edit({ filterList });
    },
    edit(parmas, notTip = false) {
      parmas.tabId = this.tabId;
      setGlobalFilter(parmas).then((res) => {
        if (res.code === 200) {
          if (!notTip) this.$message.success('保存成功');
          this.closeDialog();
          localStorage.removeItem(`globalFilterParams${this.tabId}`);
          this.$emit('freshData');
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.$emit('freshData', parmas.filterList);
        this.closeDialog();
      });
    },
    openDialog(filter) {
      this.filterList = JSON.parse(JSON.stringify(filter));
      this.getOptionsData();
      this.dialogFormVisible = true;
      const clientHeight = window.innerHeight;
      const tableHeight = Math.floor((clientHeight * 3) / 5);
      this.tableHeight = tableHeight;
    },
    closeDialog() {
      this.dialogFormVisible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.btn-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.filter-dialog {
  &::v-deep {
    .el-dialog {
      width: 700px !important;
    }
  }
}
.filter-item {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  &::v-deep {
    .selectSystemField {
      .width70 {
        .el-input__inner {
         width: 80px !important;
        }
      }
      .dept-select {
        width: 240px !important;
        .el-input__inner{
          width: 240px !important;
        }
      }
      .el-number-range {
        .input-range-val {
          width: 110px !important;
          .el-input__inner {
            width: 110px !important;
          }
        }
      }
      .filter-180 {
        width: 240px !important;
        margin-right: 10px;
        .el-input__inner {
          width: 240px !important;
        }
      }
    }
    .el-date-editor {
      width: 240px;
      margin-right: 10px;
    }
    .filter-120 {
      margin-right: 10px;
      .el-input__inner {
        width: 110px !important;
        color: #606266;
      }
    }
    .filter-80 {
      margin-right: 10px;
      .el-input__inner {
        width: 80px !important;
        color: #606266;
      }
    }
  }
}
.icon {
  cursor: pointer;
  font-size: 14px;
}
.main {
  overflow: hidden;
}
.empty {
  margin: 30px auto;
  text-align: center;
  font-size: 14px;
}
.scroll {
  @include scrollBar();
}
.delete-btn {
  font-size: 14px;
  font-family: PingFang SC, PingFang SC-Medium;
  font-weight: 500;
  color: #192452;
  margin-left: 5px;
  cursor: pointer;
  white-space: nowrap;
}
</style>
